import React from 'react';
import { useQuery } from 'react-query';
import { Link } from 'react-router-dom';
import {
  ClipboardDocumentListIcon,
  FolderIcon,
  UserGroupIcon,
  ClockIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';

const Dashboard = () => {
  // 获取仪表盘数据
  const { data: dashboardData, isLoading } = useQuery('dashboard', async () => {
    const [tasksRes, projectsRes, teamsRes] = await Promise.all([
      api.get('/tasks/my-tasks'),
      api.get('/projects'),
      api.get('/teams'),
    ]);
    
    return {
      tasks: tasksRes.data.tasks,
      projects: projectsRes.data.projects,
      teams: teamsRes.data.teams,
    };
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  const { tasks = [], projects = [], teams = [] } = dashboardData || {};

  // 统计数据
  const stats = {
    totalTasks: tasks.length,
    completedTasks: tasks.filter(task => task.status === 'done').length,
    inProgressTasks: tasks.filter(task => task.status === 'in_progress').length,
    overdueTasks: tasks.filter(task => {
      if (!task.due_date) return false;
      return new Date(task.due_date) < new Date() && task.status !== 'done';
    }).length,
    totalProjects: projects.length,
    totalTeams: teams.length,
  };

  const recentTasks = tasks.slice(0, 5);
  const recentProjects = projects.slice(0, 3);

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">仪表盘</h1>
        <p className="mt-1 text-sm text-gray-500">
          欢迎回来！这是您的工作概览。
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        <div className="card">
          <div className="card-body">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ClipboardDocumentListIcon className="h-8 w-8 text-primary-600" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">总任务数</dt>
                  <dd className="text-lg font-medium text-gray-900">{stats.totalTasks}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-body">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <CheckCircleIcon className="h-8 w-8 text-success-600" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">已完成</dt>
                  <dd className="text-lg font-medium text-gray-900">{stats.completedTasks}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-body">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ClockIcon className="h-8 w-8 text-warning-600" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">进行中</dt>
                  <dd className="text-lg font-medium text-gray-900">{stats.inProgressTasks}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-body">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ExclamationTriangleIcon className="h-8 w-8 text-danger-600" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">已过期</dt>
                  <dd className="text-lg font-medium text-gray-900">{stats.overdueTasks}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* 最近任务 */}
        <div className="card">
          <div className="card-header">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-900">最近任务</h3>
              <Link
                to="/tasks"
                className="text-sm font-medium text-primary-600 hover:text-primary-500"
              >
                查看全部
              </Link>
            </div>
          </div>
          <div className="card-body">
            {recentTasks.length > 0 ? (
              <div className="space-y-3">
                {recentTasks.map((task) => (
                  <div key={task.id} className="flex items-center justify-between">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {task.title}
                      </p>
                      <p className="text-sm text-gray-500">
                        {task.project?.name || '无项目'}
                      </p>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className={`status-badge status-${task.status.replace('_', '-')}`}>
                        {task.status === 'todo' && '待办'}
                        {task.status === 'in_progress' && '进行中'}
                        {task.status === 'review' && '审核中'}
                        {task.status === 'done' && '已完成'}
                        {task.status === 'cancelled' && '已取消'}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-6">
                <ClipboardDocumentListIcon className="mx-auto h-12 w-12 text-gray-400" />
                <h3 className="mt-2 text-sm font-medium text-gray-900">暂无任务</h3>
                <p className="mt-1 text-sm text-gray-500">开始创建您的第一个任务吧！</p>
                <div className="mt-6">
                  <Link
                    to="/tasks"
                    className="btn-primary"
                  >
                    创建任务
                  </Link>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 最近项目 */}
        <div className="card">
          <div className="card-header">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-900">最近项目</h3>
              <Link
                to="/projects"
                className="text-sm font-medium text-primary-600 hover:text-primary-500"
              >
                查看全部
              </Link>
            </div>
          </div>
          <div className="card-body">
            {recentProjects.length > 0 ? (
              <div className="space-y-3">
                {recentProjects.map((project) => (
                  <div key={project.id} className="flex items-center justify-between">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {project.name}
                      </p>
                      <p className="text-sm text-gray-500">
                        {project.description || '无描述'}
                      </p>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className="text-sm text-gray-500">
                        {project.task_count || 0} 个任务
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-6">
                <FolderIcon className="mx-auto h-12 w-12 text-gray-400" />
                <h3 className="mt-2 text-sm font-medium text-gray-900">暂无项目</h3>
                <p className="mt-1 text-sm text-gray-500">开始创建您的第一个项目吧！</p>
                <div className="mt-6">
                  <Link
                    to="/projects"
                    className="btn-primary"
                  >
                    创建项目
                  </Link>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 快速操作 */}
      <div className="card">
        <div className="card-header">
          <h3 className="text-lg font-medium text-gray-900">快速操作</h3>
        </div>
        <div className="card-body">
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            <Link
              to="/tasks"
              className="relative rounded-lg border border-gray-300 bg-white px-6 py-5 shadow-sm flex items-center space-x-3 hover:border-gray-400 focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-primary-500"
            >
              <ClipboardDocumentListIcon className="h-6 w-6 text-primary-600" />
              <div className="flex-1 min-w-0">
                <span className="absolute inset-0" aria-hidden="true" />
                <p className="text-sm font-medium text-gray-900">创建任务</p>
                <p className="text-sm text-gray-500">添加新的任务</p>
              </div>
            </Link>

            <Link
              to="/projects"
              className="relative rounded-lg border border-gray-300 bg-white px-6 py-5 shadow-sm flex items-center space-x-3 hover:border-gray-400 focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-primary-500"
            >
              <FolderIcon className="h-6 w-6 text-primary-600" />
              <div className="flex-1 min-w-0">
                <span className="absolute inset-0" aria-hidden="true" />
                <p className="text-sm font-medium text-gray-900">创建项目</p>
                <p className="text-sm text-gray-500">组织您的任务</p>
              </div>
            </Link>

            <Link
              to="/teams"
              className="relative rounded-lg border border-gray-300 bg-white px-6 py-5 shadow-sm flex items-center space-x-3 hover:border-gray-400 focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-primary-500"
            >
              <UserGroupIcon className="h-6 w-6 text-primary-600" />
              <div className="flex-1 min-w-0">
                <span className="absolute inset-0" aria-hidden="true" />
                <p className="text-sm font-medium text-gray-900">创建团队</p>
                <p className="text-sm text-gray-500">邀请团队成员</p>
              </div>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
